package rad.framework.jsf;

import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

public class PercentConverter implements Converter {

	public Object getAsObject(FacesContext context, UIComponent comp,
			String value) throws ConverterException {
		// System.out.println("PercentConverter.getAsObject: " + value);
		if (value == null || value.trim().length() == 0) {
			return null;
		}
		Double percent = null;
		NumberFormat format = NumberFormat.getNumberInstance(context
				.getViewRoot().getLocale());
		try {
			percent = new Double(format.parse(value).doubleValue());
		} catch (ParseException e) {
			throw new ConverterException(getMessage(), e);
		}
		return percent / 100;
	}

	public String getAsString(FacesContext ctx, UIComponent comp, Object object)
			throws ConverterException {
		// System.out.println("PercentConverter.getAsString: " + object);
		if (object == null) {
			return null;
		}
		Object percent = object;
		if (percent instanceof Double) {
			Double p = (Double) percent;
			percent = p * 100;
		}

		NumberFormat formatter = new DecimalFormat("#.##");
		return formatter.format(percent);
	}

	private FacesMessage getMessage() {
		ResourceBundle bundle = org.jboss.seam.core.ResourceBundle.instance();
		String summary = bundle
				.getString("javax.faces.converter.NumberConverter.PERCENT");
		String detail = bundle
				.getString("javax.faces.converter.NumberConverter.PERCENT_detail");
		return new FacesMessage(FacesMessage.SEVERITY_ERROR, summary, detail);
	}
}
